package com.hk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hk.constant.JwtConstant;
import com.hk.constant.StatusConstant;
import com.hk.exception.BaseException;
import com.hk.mapper.EmployeeMapper;
import com.hk.model.dto.LoginDto;
import com.hk.model.pojo.Employee;
import com.hk.model.vo.LoginVO;
import com.hk.msg.ExceptionMessage;
import com.hk.properties.JwtProperties;
import com.hk.service.EmployeeService;
import com.hk.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 员工登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVO login(LoginDto loginDto) {
        //验证验证码是否正确
        String captchaText = redisTemplate.opsForValue().get("captcha:" + loginDto.getUuid());
        if (!StringUtils.hasText(captchaText)) {
            throw new BaseException(ExceptionMessage.CAPTCHA_ERROR);
        }
        if (!captchaText.equals(loginDto.getCode())) {
            throw new BaseException(ExceptionMessage.CAPTCHA_ERROR);
        }

        Employee employee = employeeMapper.selectEmpByUserName(loginDto.getUsername());
        //用户名不存在
        if (ObjectUtils.isEmpty(employee)) {
            throw new BaseException(ExceptionMessage.USER_INEXISTENCE);
        }
        //密码不对
        if (!employee.getPassword().equals(loginDto.getPassword())) {
            throw new BaseException(ExceptionMessage.PASSWORD_ERROR);
        }
        //账号被锁定
        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            throw new BaseException(ExceptionMessage.USER_LOCKED);
        }

        //封装token
        HashMap<String, Object> empInfo = new HashMap<>();
        empInfo.put(JwtConstant.USER_INFO, employee.getUserName());

        String token = JwtUtil.generateJwt(empInfo);

        return LoginVO.builder().token(token).msg("登录成功").code(200).build();
    }

}
